package com.example.heimashop.view.fragment;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.heimashop.base.BaseFragment;
import com.example.heimashop.database.CartDao;
import com.example.heimashop.databinding.FragmentCartBinding;
import com.example.heimashop.model.CartItem;
import com.example.heimashop.utils.ToastUtils;
import com.example.heimashop.view.activity.OrderConfirmActivity;
import com.example.heimashop.view.adapter.CartAdapter;

import java.util.List;
import java.util.Locale;

/**
 * 购物车Fragment
 * 页面5: CartFragment - 购物车页面
 */
public class CartFragment extends BaseFragment<FragmentCartBinding> {

    private CartAdapter adapter;
    private CartDao cartDao;
    private List<CartItem> cartItems;
    private ActivityResultLauncher<Intent> orderConfirmLauncher;

    @Override
    protected FragmentCartBinding getViewBinding(LayoutInflater inflater, ViewGroup container) {
        return FragmentCartBinding.inflate(inflater, container, false);
    }

    @Override
    protected void initView() {
        cartDao = new CartDao(requireContext());

        binding.rvCart.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new CartAdapter();
        binding.rvCart.setAdapter(adapter);

        // 注册订单确认Activity Result
        orderConfirmLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == getActivity().RESULT_OK) {
                        // 订单提交成功，刷新购物车
                        loadCartData();
                    }
                }
        );

        setupAdapter();
    }

    @Override
    protected void initData() {
        loadCartData();
    }

    @Override
    protected void initListener() {
        // 全选按钮
        binding.cbAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (cartDao != null) {
                cartDao.updateAllChecked(isChecked);
                loadCartData();
            }
        });

        // 结算按钮
        binding.btnCheckout.setOnClickListener(v -> {
            // 检查是否有选中的商品
            boolean hasChecked = false;
            if (cartItems != null) {
                for (CartItem item : cartItems) {
                    if (item.isChecked()) {
                        hasChecked = true;
                        break;
                    }
                }
            }

            if (hasChecked) {
                // 跳转到订单确认页面
                Intent intent = new Intent(getContext(), OrderConfirmActivity.class);
                orderConfirmLauncher.launch(intent);
            } else {
                ToastUtils.showShort(requireContext(), "请选择要结算的商品");
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        // 每次回到购物车页面时刷新数据
        loadCartData();
    }

    /**
     * 设置适配器监听
     */
    private void setupAdapter() {
        adapter.setListener(new CartAdapter.OnCartItemListener() {
            @Override
            public void onCheckedChanged(CartItem item, boolean isChecked) {
                cartDao.updateChecked(item.getId(), isChecked);
                item.setChecked(isChecked);
                updateTotalPrice();
            }

            @Override
            public void onCountChanged(CartItem item, int count) {
                cartDao.updateCount(item.getId(), count);
                item.setGoodsCount(count);
                updateTotalPrice();
            }

            @Override
            public void onDelete(CartItem item) {
                cartDao.deleteCartItem(item.getId());
                loadCartData();
                ToastUtils.showShort(requireContext(), "已删除");
            }
        });
    }

    /**
     * 加载购物车数据
     */
    private void loadCartData() {
        if (cartDao != null) {
            cartItems = cartDao.getAllCartItems();
            adapter.setData(cartItems);

            // 假设有一个empty view，如果没有则忽略
            if (cartItems.isEmpty()) {
                binding.rvCart.setVisibility(android.view.View.GONE);
            } else {
                binding.rvCart.setVisibility(android.view.View.VISIBLE);
                updateTotalPrice();
                updateSelectAllCheckbox();
            }
        }
    }

    /**
     * 更新总价
     */
    private void updateTotalPrice() {
        double totalPrice = calculateTotalPrice();
        binding.tvTotalPrice.setText(String.format(Locale.CHINA, "¥%.2f", totalPrice));
    }

    /**
     * 计算总价
     */
    private double calculateTotalPrice() {
        double total = 0;
        if (cartItems != null) {
            for (CartItem item : cartItems) {
                if (item.isChecked()) {
                    total += item.getGoodsPrice() * item.getGoodsCount();
                }
            }
        }
        return total;
    }

    /**
     * 更新全选状态
     */
    private void updateSelectAllCheckbox() {
        if (cartItems != null && !cartItems.isEmpty()) {
            boolean allChecked = true;
            for (CartItem item : cartItems) {
                if (!item.isChecked()) {
                    allChecked = false;
                    break;
                }
            }
            binding.cbAll.setOnCheckedChangeListener(null);
            binding.cbAll.setChecked(allChecked);
            binding.cbAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
                cartDao.updateAllChecked(isChecked);
                loadCartData();
            });
        }
    }
}
